﻿<%@ WebHandler Language="C#" Class="UploadImg" %>
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Text.RegularExpressions;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using LitJson;
using System.Text;

using BusinessLogic.ClassFactory;
using BusinessLogic.BusinessRules;
using RichECMS;

/// <summary>
/// UploadImg 的摘要说明
/// </summary>
public class UploadImg : IHttpHandler, IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        //context.Response.ContentType = "text/plain";
        context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
        context.Response.Charset = "utf-8";

        if (RichECMS.State.LoginUser.IssuePath == null)
        //if (((SessionUser)context.Session["SessionUser"]).IssuePath == null)
        {
            context.Response.Write("请登陆后台后进行操作");
            return;
        }

        HttpPostedFile file = context.Request.Files["Filedata"];
        string uploadPath = context.Server.MapPath("~/")+"news\\"+State.LoginUser.VartualPath + "\\Pcfiles\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";
        String imgUrl = DateTime.Now.ToString("yyyyMMdd") + "/";
        String strMiniImgName = "";
        Hashtable resultJson = new Hashtable();
        if (file != null)
        {
            try
            {
                //bool bolEnableNameFilter = true;
                //Regex re = new Regex(@"^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$", RegexOptions.IgnoreCase);
                //string onlyfilename = file.FileName.Trim().Remove(file.FileName.LastIndexOf('.'));
                //if (bolEnableNameFilter)
                //{
                //    if (!re.IsMatch(onlyfilename))
                //    {
                //        StringBuilder errorMessage = new StringBuilder();
                //        errorMessage.Append(@"您上传的文件名里含有非法字符，请输入字母，数字 下划线的组合，下划线不能再开头或结尾,名字中不能含有空格");
                //        resultJson["status"] = false;
                //        resultJson["errorMessage"] = errorMessage.ToString();
                //        context.Response.Write(JsonMapper.ToJson(resultJson));
                //        return;
                //    }
                //}
                
                //if (onlyfilename.Length > 50)
                //{
                //    StringBuilder errorMessage = new StringBuilder();
                //    errorMessage.Append(@"您要上传的文件名太长，请不要超过25个汉字或50个字母，并且文件名里含有非法字符，请输入字母，数字 下划线的组合，下划线不能再开头或结尾,名字中不能含有空格");
                //    resultJson["status"] = false;
                //    resultJson["errorMessage"] = errorMessage.ToString();
                //    context.Response.Write(JsonMapper.ToJson(resultJson));
                //    return;
                //}

                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                string strTime = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
                string filenamestring = strTime + Path.GetExtension(file.FileName.Trim()).ToLower();
                //var filenamestring =   file.FileName;
                //var filenamestring = file.FileName.Replace("nEO_IMG_","");

                if (IsImage(file) == "true")
                {
                    //处理图片，过滤有害代码
                    using (MemoryStream memostr = new MemoryStream())
                    {
                        Image imgtemp = Image.FromStream(file.InputStream);
                        //if (imgtemp.Width > 1024 || imgtemp.Height > 1024)
                        //{
                        //    KiResizeImage(imgtemp, uploadPath + filenamestring, 1024, 1024, 1);
                        //}
                        //else
                        //{
                            //imgtemp.Save(uploadPath + filenamestring, ImageFormat.Jpeg);
							file.SaveAs(uploadPath + filenamestring);
                        //}
                        imgtemp.Dispose();
                        memostr.Dispose();

                        string strOlnyName = filenamestring.Remove(filenamestring.LastIndexOf('.'));
                        string strExtensionName = filenamestring.Remove(0, filenamestring.LastIndexOf('.'));
                        strMiniImgName = strOlnyName + "mini" + strExtensionName;

                        //生成缩略图
                        KiResizeImage(uploadPath + filenamestring, uploadPath + strMiniImgName, 430, 430, 1);

                        //插入资源表
                        /*
                        using (UserFileFactory objFactory = new UserFileFactory())
                        {
                            UserFile objUserFile= objFactory.NewInstance();
                            objUserFile.DataItem.chvFileDestription = "";
                            objUserFile.DataItem.chvFileName = filenamestring;
                            objUserFile.DataItem.chvFilePath = imgUrl+filenamestring;
                            objUserFile.DataItem.chvMiniFileName = strMiniImgName;
                            objUserFile.DataItem.chvMiniFilePath = imgUrl + strMiniImgName;
                            objUserFile.DataItem.chvUpLoadMan = State.LoginUser.LoginName;
                            objUserFile.DataItem.dtmUpLoadTime = DateTime.Now;
                            objUserFile.DataItem.intArticleID = -1;
                            objUserFile.DataItem.intFileSize = file.ContentLength / 1024;
                            objUserFile.DataItem.intFileType
                        }
                        */

                        resultJson = new Hashtable();
                        resultJson["status"] = true;
                        resultJson["filepath"] = imgUrl + strMiniImgName;
                        context.Response.Write(JsonMapper.ToJson(resultJson));
                    }
                }
                else
                {
                    StringBuilder errorMessage = new StringBuilder();
                    errorMessage.Append(@"请上传图片类型文件");
                    resultJson["status"] = false;
                    resultJson["errorMessage"] = errorMessage.ToString();
                    context.Response.Write(JsonMapper.ToJson(resultJson));
                }
            }
            catch (Exception error)
            {
                if (!File.Exists(context.Server.MapPath(context.Request.Path).Replace("IHandler\\UploadImg.ashx", "") + "log.txt"))
                {
                    File.Create(context.Server.MapPath(context.Request.Path).Replace("IHandler\\UploadImg.ashx", "") + "log.txt");
                }

                using (FileStream filelog = new FileStream(context.Server.MapPath(context.Request.Path).Replace("IHandler\\UploadImg.ashx", "") + "log.txt", FileMode.Append, FileAccess.Write))
                {
                    StreamWriter sw = new StreamWriter(filelog);
                    sw.WriteLine(DateTime.Now.ToString() + "    源:" + error.Source + "    信息:" + error.Message);
                    sw.Close();
                }
            }
        }
        else
        {
            context.Response.Write("上传失败");
        }
    }

    ////过滤文件类型
    //private static bool FileTypeFilter(string filename)
    //{
    //    List<string> filteType = new List<string>() { "aspx", "asp", "php", "dll" };

    //    string [] nameSplit = filename.Split('.');

    //    if (nameSplit.Length > 0)
    //    {
    //        string nameExtension = nameSplit[nameSplit.Length - 1];

    //        if (filteType.Contains(nameExtension))
    //        {
    //            return false;
    //        }
    //        else
    //        {
    //            return true;
    //        }
    //    }
    //    else
    //    {
    //        return false;
    //    }
    //}

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    #region

    public static bool ImgWidthBiggerThenHeight(string url)
    {
        Image img = Image.FromFile(url);
        try
        {
            if (img.Width >= img.Height)
            {
                img.Dispose();
                return true;
            }
            else
            {
                img.Dispose();
                return false;
            }

        }
        catch (Exception imgerror)
        {
            return false;
        }
    }

    public static string IsImage(HttpPostedFile postfile)
    {
        try
        {
            using (Image img = Image.FromStream(postfile.InputStream))
            {
                MemoryStream memoimg = new MemoryStream();
                img.Save(memoimg, ImageFormat.Jpeg);
                img.Dispose();
                return "true";
            }
        }
        catch (Exception)
        {
            return "false";
        }

        //var img = Image.FromStream(postfile.InputStream);
        //var memoimg = new MemoryStream();
        //try
        //{
        //    img.Save(memoimg, ImageFormat.Jpeg);
        //    img.Dispose();
        //    return "true";
        //}
        //catch (Exception imgerror)
        //{
        //    return imgerror.Message;
        //}
        //finally
        //{
        //    memoimg.Dispose();
        //}
    }

    public static bool IsImageByUploadFile(HttpPostedFile postfile)
    {
        try
        {
            //var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(postfile.InputStream);
            byte[] b = new byte[2];
            byte buffer = reader.ReadByte();
            b[0] = buffer;
            string fileClass = buffer.ToString();
            buffer = reader.ReadByte();
            b[1] = buffer;
            fileClass += buffer.ToString();


            reader.Close();
            //fs.Close();
            if (fileClass == "255216" || fileClass == "7173" || fileClass == "6677" || fileClass == "13780")//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch
        {
            return false;
        }

        //var img = Image.FromStream(postfile.InputStream);
        //var memoimg = new MemoryStream();
        //try
        //{
        //    img.Save(memoimg, ImageFormat.Jpeg);
        //    img.Dispose();
        //    return "true";
        //}
        //catch (Exception imgerror)
        //{
        //    return imgerror.Message;
        //}
        //finally
        //{
        //    memoimg.Dispose();
        //}
    }

    public static bool IsImage(string path)
    {
        try
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(fs);
            byte[] b = new byte[2];
            byte buffer = reader.ReadByte();
            b[0] = buffer;
            string fileClass = buffer.ToString();
            buffer = reader.ReadByte();
            b[1] = buffer;
            fileClass += buffer.ToString();


            reader.Close();
            fs.Close();
            if (fileClass == "255216" || fileClass == "7173" || fileClass == "6677" || fileClass == "13780")//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch
        {
            return false;
        }
    }

    #endregion

    #region 绘制缩略图

    /// <summary>
    /// Resize图片
    /// </summary>
    /// <param name="bmp">原始Bitmap</param>
    /// <param name="newW">新的宽度</param>
    /// <param name="newH">新的高度</param>
    /// <param name="mode">保留着，暂时未用</param>
    /// <returns>处理以后的图片</returns>
    private static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH, int mode)
    {
        Bitmap b = new Bitmap(newW, newH);
        try
        {
            Graphics g = Graphics.FromImage(b);
            // 插值算法的质量
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            // 高质量
            g.SmoothingMode = SmoothingMode.HighQuality;

            g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
            g.Dispose();
            return b;
        }
        catch
        {
            return null;
        }
        //finally
        //{
        //    b.Dispose();
        //}
    }

    /// <summary>
    ///  缩放
    /// </summary>
    /// <param name="imageUrl"></param>
    /// <param name="savePath"></param>
    /// <param name="newW"></param>
    /// <param name="newH"></param>
    /// <param name="mode"></param>
    /// <returns></returns>
    public static void KiResizeImage(string imageUrl, string savePath, int newW, int newH, int mode)
    {
        Image image = System.Drawing.Image.FromFile(imageUrl);

        int tHeight = 0;
        int tWidth = 0;

        //按比例计算出缩略图的宽度和高度
        if (image.Width >= image.Height)
        {
            if (newW < image.Width)
            {
                tHeight = (int)Math.Floor(Convert.ToDouble(image.Height) * (Convert.ToDouble(newW)
                / Convert.ToDouble(image.Width)));
                tWidth = newW;
            }
            else
            {
                tHeight = image.Height;
                tWidth = image.Width;
            }
        }
        else
        {
            if (newH < image.Height)
            {
                tWidth = (int)Math.Floor(Convert.ToDouble(image.Width) * (Convert.ToDouble(newH)
                / Convert.ToDouble(image.Height)));
                tHeight = newH;
            }
            else
            {
                tHeight = image.Height;
                tWidth = image.Width;
            }
        }

        Bitmap nbm = new Bitmap(image, image.Width, image.Height);
        try
        {
            image = KiResizeImage(nbm, tWidth, tHeight, mode);
            if (File.Exists(savePath))
                File.Delete(savePath);
            image.Save(savePath, ImageFormat.Jpeg);
        }
        catch
        {
            throw;
        }
    }

    public static void KiResizeImage(Image image, string savePath, int newW, int newH, int mode)
    {
        int tHeight = 0;
        int tWidth = 0;

        //按比例计算出缩略图的宽度和高度
        if (image.Width >= image.Height)
        {
            if (newW < image.Width)
            {
                tHeight = (int)Math.Floor(Convert.ToDouble(image.Height) * (Convert.ToDouble(newW)
                / Convert.ToDouble(image.Width)));
                tWidth = newW;
            }
            else
            {
                tHeight = image.Height;
                tWidth = image.Width;
            }
        }
        else
        {
            if (newH > image.Height)
            {
                tWidth = (int)Math.Floor(Convert.ToDouble(image.Width) * (Convert.ToDouble(newH)
                / Convert.ToDouble(image.Height)));
                tHeight = newH;
            }
            else
            {
                tHeight = image.Height;
                tWidth = image.Width;
            }
        }

        Bitmap nbm = new Bitmap(image, image.Width, image.Height);
        try
        {
            image = KiResizeImage(nbm, tWidth, tHeight, mode);
            if (File.Exists(savePath))
                File.Delete(savePath);
            image.Save(savePath, ImageFormat.Jpeg);
        }
        catch
        {
            throw;
        }
    }

    #endregion
}